class WebRTCClient {
    constructor() {
        this.ws = null;
        this.userId = null;
        this.userName = null;
        this.peerConnection = null;
        this.localStream = null;
        this.remoteStream = null;
        this.currentCall = null;
        
        // WebRTC 配置
        this.rtcConfig = {
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' },
                { urls: 'stun:stun1.l.google.com:19302' }
            ]
        };
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.connectWebSocket();
        this.setupMedia();
    }
    
    /**
     * 设置所有UI事件监听器
     * 
     * 该方法负责为WebRTC客户端的所有用户界面元素绑定事件处理函数，
     * 包括登出按钮、通话控制按钮（视频切换、音频切换、挂断）以及来电处理按钮。
     * 
     * @memberof WebRTCClient
     * @returns {void}
     */
    setupEventListeners() {
        // 登出按钮
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });
        
        // 通话控制按钮
        document.getElementById('toggleVideo').addEventListener('click', () => {
            this.toggleVideo();
        });
        
        document.getElementById('toggleAudio').addEventListener('click', () => {
            this.toggleAudio();
        });
        
        document.getElementById('hangupBtn').addEventListener('click', () => {
            this.hangup();
        });
        
        // 来电处理
        document.getElementById('acceptCall').addEventListener('click', () => {
            this.acceptCall();
        });
        
        document.getElementById('rejectCall').addEventListener('click', () => {
            this.rejectCall();
        });
    }
    
    // 连接 WebSocket
    connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}`;
        
        this.ws = new WebSocket(wsUrl);
        
        this.ws.onopen = () => {
            console.log('WebSocket 连接已建立');
            this.login();
        };
        
        this.ws.onmessage = (event) => {
            this.handleMessage(JSON.parse(event.data));
        };
        
        this.ws.onclose = () => {
            console.log('WebSocket 连接已关闭');
            // 尝试重新连接
            setTimeout(() => this.connectWebSocket(), 3000);
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
        };
    }
    
    // 处理服务器消息
    handleMessage(message) {
        const { type, data } = message;
        
        switch (type) {
            case 'login_success':
                this.handleLoginSuccess(data);
                break;
            case 'user_list':
                this.updateUserList(data.users);
                break;
            case 'call_request':
                this.handleIncomingCall(data);
                break;
            case 'call_response':
                this.handleCallResponse(data);
                break;
            case 'offer':
                this.handleOffer(data);
                break;
            case 'answer':
                this.handleAnswer(data);
                break;
            case 'ice_candidate':
                this.handleIceCandidate(data);
                break;
            case 'hangup':
                this.handleRemoteHangup(data);
                break;
            case 'error':
                this.showError(data.message);
                break;
        }
    }
    
    /**
     * 发送消息到服务器
     * 
     * @param {Object} message - 要发送的消息对象
     * @param {string} message.type - 消息类型
     * @param {Object} message.data - 消息数据
     */
    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        }
    }
    
    // 用户登录
    login() {
        const userName = localStorage.getItem('userName');
        if (!userName) {
            window.location.href = '/';
            return;
        }
        
        this.userName = userName;
        document.getElementById('userNameDisplay').textContent = userName;
        
        this.sendMessage({
            type: 'login',
            data: { userName }
        });
    }
    
    // 处理登录成功
    handleLoginSuccess(data) {
        this.userId = data.userId;
        this.updateUserList(data.onlineUsers);
    }
    
    // 更新通话状态显示
    updateCallStatus() {
        if (this.currentCall) {
            const statusElement = document.getElementById('callStatus');
            const remoteUserInfo = document.getElementById('remoteUserInfo');
            const remoteVideoTitle = document.getElementById('remoteVideoTitle');
            
            if (this.currentCall.initiated) {
                // 发起方显示"正在呼叫..."
                if (statusElement) {
                    statusElement.textContent = '正在呼叫...';
                }
                if (remoteVideoTitle) {
                    remoteVideoTitle.textContent = '等待对方接听...';
                }
            } else {
                // 接听方显示"与 [对方姓名] 通话中"
                if (statusElement) {
                    statusElement.textContent = `与 ${this.currentCall.fromUserName} 通话中`;
                }
                if (remoteVideoTitle) {
                    remoteVideoTitle.textContent = `${this.currentCall.fromUserName} 的视频`;
                }
                // 显示对方信息
                this.showRemoteUserInfo(this.currentCall.fromUserName);
            }
        }
    }
    
    // 显示对方用户信息
    showRemoteUserInfo(userName) {
        const remoteUserInfo = document.getElementById('remoteUserInfo');
        const userNameDisplay = document.querySelector('.user-name-display');
        
        if (remoteUserInfo && userNameDisplay) {
            userNameDisplay.textContent = userName;
            remoteUserInfo.style.display = 'flex';
        }
    }
    
    // 隐藏对方用户信息
    hideRemoteUserInfo() {
        const remoteUserInfo = document.getElementById('remoteUserInfo');
        if (remoteUserInfo) {
            remoteUserInfo.style.display = 'none';
        }
    }
    
    // 更新发起方的通话状态
    updateCallStatusForInitiator(remoteUserName) {
        const statusElement = document.getElementById('callStatus');
        const remoteVideoTitle = document.getElementById('remoteVideoTitle');
        
        if (statusElement) {
            statusElement.textContent = `与 ${remoteUserName} 通话中`;
        }
        
        if (remoteVideoTitle) {
            remoteVideoTitle.textContent = `${remoteUserName} 的视频`;
        }
    }
    
    // 更新用户列表
    updateUserList(users) {
        const userListElement = document.getElementById('userList');
        userListElement.innerHTML = '';
        
        users.forEach(user => {
            if (user.id !== this.userId) {
                const userElement = document.createElement('div');
                userElement.className = 'user-item';
                
                // 根据用户状态显示不同的按钮和样式
                let buttonHtml = '';
                let statusClass = '';
                
                if (user.inCall) {
                    buttonHtml = '<span class="status-badge in-call">通话中</span>';
                    statusClass = 'in-call';
                } else {
                    buttonHtml = '<button class="call-btn" data-user-id="' + user.id + '">呼叫</button>';
                    statusClass = 'available';
                }
                
                userElement.className = `user-item ${statusClass}`;
                userElement.innerHTML = `
                    <span class="user-name">${user.name}</span>
                    <span class="user-status">${user.status}</span>
                    ${buttonHtml}
                `;
                userListElement.appendChild(userElement);
                
                // 只有非通话中的用户才能被呼叫
                if (!user.inCall) {
                    userElement.querySelector('.call-btn').addEventListener('click', () => {
                        this.startCall(user.id);
                    });
                }
            }
        });
    }
    
    // 开始呼叫
    async startCall(toUserId) {
        if (this.currentCall) {
            this.showError('您正在通话中');
            return;
        }
        
        this.currentCall = {
            toUserId,
            initiated: true
        };
        
        // 只发送呼叫请求，不立即创建WebRTC连接
        this.sendMessage({
            type: 'call_request',
            data: { toUserId }
        });
        
        this.updateUIForCall(true);
    }
    
    // 处理来电
    handleIncomingCall(data) {
        this.currentCall = {
            fromUserId: data.fromUserId,
            fromUserName: data.fromUserName,
            initiated: false
        };
        
        // 显示来电对话框
        document.getElementById('callerName').textContent = data.fromUserName;
        document.getElementById('incomingCallModal').style.display = 'block';
    }
    
    // 接听来电
    async acceptCall() {
        document.getElementById('incomingCallModal').style.display = 'none';
        
        // 发送呼叫接受响应
        this.sendMessage({
            type: 'call_response',
            data: {
                toUserId: this.currentCall.fromUserId,
                accepted: true
            }
        });
        
        this.updateUIForCall(true);
        // 更新通话状态显示
        this.updateCallStatus();
    }
    
    // 拒绝来电
    rejectCall() {
        document.getElementById('incomingCallModal').style.display = 'none';
        
        this.sendMessage({
            type: 'call_response',
            data: {
                toUserId: this.currentCall.fromUserId,
                accepted: false
            }
        });
        
        this.currentCall = null;
    }
    
    // 处理呼叫响应
    async handleCallResponse(data) {
        if (!data.accepted) {
            this.showError('对方拒绝了您的呼叫');
            this.hangup();
            return;
        }
        
        // 对方接受呼叫后，开始建立WebRTC连接
        try {
            // 创建 PeerConnection
            this.createPeerConnection();
            
            // 添加本地流
            if (this.localStream) {
                this.localStream.getTracks().forEach(track => {
                    this.peerConnection.addTrack(track, this.localStream);
                });
            }
            
            // 创建并发送 Offer
            const offer = await this.peerConnection.createOffer();
            await this.peerConnection.setLocalDescription(offer);
            
            this.sendMessage({
                type: 'offer',
                data: {
                    toUserId: this.currentCall.toUserId,
                    offer
                }
            });
            
            // 更新发起方的通话状态 - 显示与对方通话中
            this.updateCallStatusForInitiator(data.fromUserName || '对方');
            
            // 显示对方信息（发起方）
            this.showRemoteUserInfo(data.fromUserName || '对方');
            
        } catch (error) {
            console.error('建立WebRTC连接失败:', error);
            this.showError('连接失败');
            this.hangup();
        }
    }
    
    // 创建 PeerConnection
    createPeerConnection() {
        this.peerConnection = new RTCPeerConnection(this.rtcConfig);
        
        // 处理远程流
        this.peerConnection.ontrack = (event) => {
            const remoteVideo = document.getElementById('remoteVideo');
            if (event.streams && event.streams[0]) {
                remoteVideo.srcObject = event.streams[0];
                this.remoteStream = event.streams[0];
            }
        };
        
        // 处理 ICE 候选
        this.peerConnection.onicecandidate = (event) => {
            if (event.candidate && this.currentCall) {
                const toUserId = this.currentCall.initiated ? 
                    this.currentCall.toUserId : this.currentCall.fromUserId;
                
                this.sendMessage({
                    type: 'ice_candidate',
                    data: {
                        toUserId,
                        candidate: event.candidate
                    }
                });
            }
        };
        
        // 处理连接状态
        this.peerConnection.onconnectionstatechange = () => {
            console.log('连接状态:', this.peerConnection.connectionState);
            
            if (this.peerConnection.connectionState === 'connected') {
                console.log('WebRTC 连接已建立');
            } else if (this.peerConnection.connectionState === 'disconnected' ||
                      this.peerConnection.connectionState === 'failed') {
                console.log('WebRTC 连接断开');
                this.hangup();
            }
        };
    }
    
    // 处理 Offer
    async handleOffer(data) {
        // 只有在接听状态下才处理Offer
        if (!this.currentCall || this.currentCall.initiated) {
            console.log('忽略Offer：未在接听状态');
            return;
        }
        
        if (!this.peerConnection) {
            this.createPeerConnection();
            
            // 添加本地流
            if (this.localStream) {
                this.localStream.getTracks().forEach(track => {
                    this.peerConnection.addTrack(track, this.localStream);
                });
            }
        }
        
        try {
            await this.peerConnection.setRemoteDescription(data.offer);
            const answer = await this.peerConnection.createAnswer();
            await this.peerConnection.setLocalDescription(answer);
            
            this.sendMessage({
                type: 'answer',
                data: {
                    toUserId: data.fromUserId,
                    answer
                }
            });
            
        } catch (error) {
            console.error('处理 Offer 失败:', error);
            this.hangup();
        }
    }
    
    // 处理 Answer
    async handleAnswer(data) {
        try {
            await this.peerConnection.setRemoteDescription(data.answer);
        } catch (error) {
            console.error('处理 Answer 失败:', error);
            this.hangup();
        }
    }
    
    // 处理 ICE 候选
    async handleIceCandidate(data) {
        try {
            await this.peerConnection.addIceCandidate(data.candidate);
        } catch (error) {
            console.error('添加 ICE 候选失败:', error);
        }
    }
    
    // 处理远程挂断
    handleRemoteHangup() {
        this.showError('对方已挂断');
        this.hangup();
    }
    
    // 挂断通话
    hangup() {
        if (this.currentCall) {
            const toUserId = this.currentCall.initiated ? 
                this.currentCall.toUserId : this.currentCall.fromUserId;
            
            this.sendMessage({
                type: 'hangup',
                data: { toUserId }
            });
        }
        
        this.cleanupCall();
    }
    
    // 清理通话资源
    cleanupCall() {
        if (this.peerConnection) {
            this.peerConnection.close();
            this.peerConnection = null;
        }
        
        // 清除远程视频
        const remoteVideo = document.getElementById('remoteVideo');
        remoteVideo.srcObject = null;
        this.remoteStream = null;
        
        // 隐藏对方信息
        this.hideRemoteUserInfo();
        
        // 重置远程视频标题
        const remoteVideoTitle = document.getElementById('remoteVideoTitle');
        if (remoteVideoTitle) {
            remoteVideoTitle.textContent = '远程视频';
        }
        
        // 重置通话状态
        const callStatus = document.getElementById('callStatus');
        if (callStatus) {
            callStatus.textContent = '等待通话...';
        }
        
        this.currentCall = null;
        this.updateUIForCall(false);
    }
    
    // 设置媒体流
    async setupMedia() {
        try {
            this.localStream = await navigator.mediaDevices.getUserMedia({
                video: true,
                audio: true
            });
            
            const localVideo = document.getElementById('localVideo');
            localVideo.srcObject = this.localStream;
            
        } catch (error) {
            console.error('获取媒体设备失败:', error);
            this.showError('无法访问摄像头或麦克风');
        }
    }
    
    // 切换视频
    toggleVideo() {
        if (this.localStream) {
            const videoTracks = this.localStream.getVideoTracks();
            if (videoTracks.length > 0) {
                const enabled = !videoTracks[0].enabled;
                videoTracks[0].enabled = enabled;
                
                const button = document.getElementById('toggleVideo');
                button.textContent = enabled ? '关闭视频' : '开启视频';
                button.classList.toggle('muted', !enabled);
            }
        }
    }
    
    // 切换音频
    toggleAudio() {
        if (this.localStream) {
            const audioTracks = this.localStream.getAudioTracks();
            if (audioTracks.length > 0) {
                const enabled = !audioTracks[0].enabled;
                audioTracks[0].enabled = enabled;
                
                const button = document.getElementById('toggleAudio');
                button.textContent = enabled ? '关闭音频' : '开启音频';
                button.classList.toggle('muted', !enabled);
            }
        }
    }
    
    // 更新通话界面
    updateUIForCall(inCall) {
        const hangupBtn = document.getElementById('hangupBtn');
        const userList = document.getElementById('userList');
        
        hangupBtn.disabled = !inCall;
        userList.style.opacity = inCall ? '0.5' : '1';
        
        // 禁用用户列表中的呼叫按钮
        const callButtons = userList.querySelectorAll('.call-btn');
        callButtons.forEach(btn => {
            btn.disabled = inCall;
        });
    }
    
    // 显示错误信息
    showError(message) {
        // 在实际应用中，可以使用更友好的方式显示错误
        alert(message);
    }
    
    // 用户登出
    logout() {
        if (this.currentCall) {
            this.hangup();
        }
        
        localStorage.removeItem('userName');
        
        if (this.ws) {
            this.ws.close();
        }
        
        window.location.href = '/';
    }
}

// 初始化 WebRTC 客户端
let webrtcClient;

document.addEventListener('DOMContentLoaded', () => {
    if (window.location.pathname === '/call') {
        webrtcClient = new WebRTCClient();
    }
});